#pragma once
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void Insert_file(char name[],int sum);

FILE *fp,*file_head,*text;
int Data_num=0;

struct Data
{
    int id;
    char name[100];
    int num;
    struct Data *next;
}*head,*nev,*p ,*now;

void Screen(){
    struct Data *p1;
    p1=head;
    while(p1!=NULL){
        printf("%-5d %-5s %-5d\n",p1->id,p1->name,p1->num);
        p1=p1->next;
    } 
}

void read(){
   char name[20];
   int num;
   int id;
   int Input_number;
   fscanf(text, "%d",&Input_number);
   for(int i=0;i<Input_number;i++){
        fscanf(fp, "%d,%d,%s",&id,&num,name);
        Insert_file(name,num);
   }
    fclose(fp);
    fclose(text);
    printf("Success\n");
}

void open()
{

    if((text = fopen("num.txt", "r+"))!=NULL&&(fp = fopen("data.csv", "r+"))!=NULL){
        read(); 
    } 
}

void Insert_file(char name[],int sum){
    //在链表末尾添加数字
    now=(struct Data*)malloc(sizeof(struct Data));
    if(head == NULL){
        nev=NULL;
        head=now;
        p=now;
        now->id=1;
        strcpy(now->name,name);
        p->num=sum;
        Data_num++;
        p->next=nev;
    }else{
        p->next=now;
        now->id=p->id+1;
        strcpy(now->name,name);
        now->num=sum;
        Data_num++;
        now->next=nev;
        p=now;
    }
}

void Save_file(){
    //将Data文件内部的数据存为.csv格式
    text = fopen("num.txt", "w+");
    fp = fopen("data.csv", "w+");
    fprintf(text, "%d", Data_num);
    p=head;
    while(p!=NULL){
        fprintf(fp,"%d,%d,%s\n",p->id,p->num,p->name);
        p=p->next;
    }
    fclose(fp);
    fclose(text);
    printf("Success\n");
}
/*
void Save_file()
{
    //remove("data.dat");
    fp = fopen("data.dat", "wb+");
    //将Data储存在data目录下
    struct Data *p;
    p=head;
    fp=file_head;
    fwrite(&Data_num,sizeof(int),1,fp);
    while(p!=NULL){

       fwrite(p,sizeof(struct Data),1,fp);
        p=p->next;
    }
    printf("Success\n");
}
*/
int Pay()
{
    int sum=0;
    while (p!=NULL)
    {
        if(p->num<0)
        sum+=p->num;
        p=p->next;
    }
    return sum;
}

int Income()
{
    int sum=0;
    while (p!=NULL)
    {
        if(p->num>0)
        sum+=p->num;
        p=p->next;
    }
    return sum;
}

void del_record(int id) {
    struct Data *p1,*p2;
    p1=head;
    p2=head;
    while (p1!=NULL){
        if(p1->id==id){
            break;
        }
        p2=p1;
        p1=p1->next;
    }
    if(p1==NULL){
        printf("没有搜到");
        return;
    }
    p2->next=p1->next;
    free(p1);
}

void find(char *Data_name)
    {
        struct Data *p1;
        p1 = head;
        while (p1 !=NULL)
        {
            if(!strcmp(p1->name,Data_name)){
                printf("%-5d %-5s %-5d\n",p1->id,p1->name,p1->num);
            }
            p1=p1->next;
        }
        
    }